package com.ydj.app.config.interceptor;

import com.ydj.app.CmsConst;
import com.ydj.app.protocol.redis.RdsCmsLoginInfo;
import com.ydj.framework.exception.VerifyTokenException;
import com.ydj.framework.filter.ExtHttpServletRequest;
import com.ydj.framework.filter.ExtHttpServletResponse;
import com.ydj.framework.interceptor.AuthBaseInterceptor;
import com.ydj.framework.redis.ExtRedisTemplate;
import com.ydj.framework.redis.RedisKey;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * CMS的拦截器
 */
@Component
public class CmsAuthInterceptor extends AuthBaseInterceptor {
	@Autowired
	private ExtRedisTemplate redisTemplate;

	@Autowired
	private CmsConst cmsConst;

	@Override
	public String getPathPatterns() {
		return cmsConst.getBaseUrl() + "/**";
	}

	@Override
	public boolean doPreHandle(ExtHttpServletRequest request, ExtHttpServletResponse response, Object handler, String token) throws VerifyTokenException {
		String key = RedisKey.getCmsToken(token);
		RdsCmsLoginInfo rdsInfo = redisTemplate.getIfExceptionDelete(key);

		// 从 Redis 中读取到的是错误格式，让前端重新走一次登录流程
		if (rdsInfo == null) {
			throw new VerifyTokenException();
		}

		Long accountId = rdsInfo.getAccountId();
		if (accountId == null) {
			redisTemplate.delete(key);
			throw new VerifyTokenException();
		}
		if (rdsInfo.getName() == null) {
			ThreadContext.put("userId", rdsInfo.getName());
		} else {
			ThreadContext.put("userId", accountId.toString());
		}

		// 续期 token
		redisTemplate.expire(key, 7, TimeUnit.DAYS);
		request.getInterceptorContext().setRdsLoginInfo(rdsInfo);
		return true;
	}
}